package com.huaxindata.im.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.Interpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huaxindata.im.R;

/**
 * Created by hebing on 2016/9/12.
 */
public class MessageSearchView extends RelativeLayout implements View.OnClickListener {
    public MessageSearchView(Context context) {
        super(context);
    }

    public MessageSearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MessageSearchView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MessageSearchView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        setupView();
    }

    EditText et_search;
    ImageView iv_search;
    TextView tv_cancel;
    TextView tv_clear;

    TextView tv_tip;

    View search_layout;

    boolean withAnim = true;
    int ivx, tipx, ivw, tipw;
    int duration = 300;

    boolean showCancel = false;
    int offset, width;

    void setupView() {
        et_search = (EditText) findViewById(R.id.et_search);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        tv_tip = (TextView) findViewById(R.id.tv_tip);
        tv_clear = (TextView) findViewById(R.id.tv_clear);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        search_layout = findViewById(R.id.search_layout);
        offset = getResources().getDimensionPixelOffset(R.dimen.click_size);

        tv_cancel.setOnClickListener(this);
        tv_clear.setOnClickListener(this);
        tv_tip.setOnClickListener(this);
        search_layout.setOnClickListener(this);

        et_search.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                //Log.d("onFocusChange:" + hasFocus);
                if (hasFocus) {
                    doSearch();
                }
            }
        });

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    tv_clear.setVisibility(GONE);
                } else {
                    tv_clear.setVisibility(VISIBLE);
                }
                if (callback != null) callback.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (ivx == 0 && withAnim) {
            ivx = (int) iv_search.getX();
            tipx = (int) tv_tip.getX();
            ivw = iv_search.getWidth() << 1;
            tipw = tv_tip.getWidth();
            tv_tip.setPivotX(0);
//            Log.d("onLayout:" + ivx + " - " + tipx);
        }
        if (width == 0 && showCancel) {
            width = search_layout.getWidth();
            mParams = (LinearLayout.LayoutParams) search_layout.getLayoutParams();
        }
    }

    public void hideSearch() {
        if (!searching) {
            return;
        }
        //Log.d("hideSearch...");
        searching = false;
        iv_search.setVisibility(View.GONE);
        if (withAnim) {
            ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f * ivw / tipw, 1, 1, 1);
            scaleAnimation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    if (input > .5f) {
                        tv_tip.setTextColor(getResources().getColor(R.color.secondary_text));
                    }
                    return input;
                }
            });
            TranslateAnimation translateAnimation = new TranslateAnimation((ivx - tipx), 0, 0, 0);
            scaleAnimation.setDuration(duration);
            translateAnimation.setDuration(duration);
            AnimationSet set = new AnimationSet(false);
            set.addAnimation(scaleAnimation);
            set.addAnimation(translateAnimation);
            tv_tip.setVisibility(View.VISIBLE);
            tv_tip.startAnimation(set);
        } else {
            tv_tip.setVisibility(View.VISIBLE);
        }

        if (showCancel)
            reLayyout(width);

        et_search.setText(null);
        et_search.clearFocus();
        hideIme();
    }

    void doSearch() {
        if (searching) {
            return;
        }
        //Log.d("doSearch...");
        searching = true;
//        tv_clear.setVisibility(View.VISIBLE);
        if (withAnim) {
            ScaleAnimation scaleAnimation = new ScaleAnimation(1, 1.0f * ivw / tipw, 1, 1);
            scaleAnimation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    if (input > .5f) {
                        tv_tip.setTextColor(getResources().getColor(R.color.transparent));
                    }
                    return input;
                }
            });
            TranslateAnimation translateAnimation = new TranslateAnimation(0, (ivx - tipx), 0, 0);
            translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    tv_tip.setVisibility(View.GONE);
                    iv_search.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            scaleAnimation.setDuration(duration);
            translateAnimation.setDuration(duration);
            AnimationSet set = new AnimationSet(false);
            set.addAnimation(scaleAnimation);
            set.addAnimation(translateAnimation);
            tv_tip.startAnimation(set);
        } else {
            iv_search.setVisibility(View.VISIBLE);
            tv_tip.setVisibility(View.GONE);
        }

        if (showCancel) {
            reLayyout(width - offset);
        }
        et_search.requestFocus();
        showIme();
    }

    void reLayyout(int width) {
        mParams.width = width;
        search_layout.setLayoutParams(mParams);
        search_layout.invalidate();
    }

    LinearLayout.LayoutParams mParams;
    boolean searching = false;

    @Override
    public void onClick(View v) {
        //Log.d("onClick :" + v);
        if (v == tv_cancel) {
            hideSearch();
        } else if (v == tv_clear) {
            et_search.setText(null);
        } else if (v == tv_tip || v == et_search || search_layout == v) {
            if (!searching)
                doSearch();
        }
    }

    public boolean isSearching() {
        return searching;
    }

    public void hideIme() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_search.getWindowToken(), 0);
    }

    public void showIme() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et_search, InputMethodManager.SHOW_FORCED);
    }


    public void setTipHint(String tipHint) {
        tv_tip.setText(tipHint);
    }

    public interface Callback {
        void onTextChanged(CharSequence sequence);
    }

    Callback callback;

    public void setCallback(Callback callback) {
        this.callback = callback;
    }
}
